package com.android.djlmapp.server;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.android.djlmapp.activity.login.LoginActivity;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.PrefUtils;

public class RefreshService extends Service {
    private RefreshTokenTools refreshTokenTools;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mHandler.removeMessages(0);
                    refreshTokenTools.refreshServ();
                    mHandler.sendEmptyMessageDelayed(0, 6000 * 1000);
//                    mHandler.sendEmptyMessageDelayed(0, 10 * 1000);
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeMessages(0);
            mHandler = null;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        refreshTokenTools = new RefreshTokenTools(getApplicationContext());
        refreshTokenTools.setRefreshTokenListener(new RefreshTokenTools.RefreshTokenListener() {
            @Override
            public void refreshTokenSuc(String token) {
                Log.e("项目异常", "------RefreshService------");
                PrefUtils.putString(ConstantsValue.TOKEN, token);
            }

            @Override
            public void refreshTokenFail() {
                exitLogin();
            }

            @Override
            public void netError() {
//                ToastUtils.showShortToast(getApplicationContext(), "网络或服务器错误");
            }
        });
        mHandler.sendEmptyMessage(0);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        // 每次开启服务的时候先刷新一遍
        refreshTokenTools.refreshServ();
    }

    private void exitLogin() {
        PrefUtils.putBoolean(ConstantsValue.IS_LOG, false);
        PrefUtils.putString( ConstantsValue.TOKEN, "");
        Intent intent = new Intent(getApplicationContext(),
                LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        mHandler.removeCallbacksAndMessages(null);
        stopSelf();
      //  if (LoginActivity.instence == null)
        {
            startActivity(intent);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}